rm(list=ls())
setwd("/Users/ac/Documents/columbia/study/2015fall/G5999 Master Thesis/Thesis Writing/GIS part /regional_2004_GWR")

library(maptools)
library (spdep)
library(spgwr)
library (rgdal)

GWR <- readShapeSpatial("cb_2014_us_state_500k.shp")

plot(GWR)

names(GWR)

spplot(GWR, "Yield")

# Delete rows with missing data
d <- GWR@data
#d <- subset(d, !is.na(d$Yield))
#GWR@data <- d

bwG <- gwr.sel(Yield ~ Temp_6 + Precip_6 + Price_Lag + Acre_Plant + Income, data=GWR, gweight=gwr.Gauss, verbose=TRUE)
# "sel" is selection
# generate fixed bandwith

gwrG <- gwr(Yield ~ Temp_6 + Precip_6 + Price_Lag + Acre_Plant + Income, data=GWR, bandwidth=bwG, gweight=gwr.Gauss)
# run the gwr regression

gwrG

names(gwrG)
# SDF is spatial data frame

names(gwrG$SDF)
# include slope, intercept, local R2, and etc.

spplot(gwrG$SDF, "localR2")


library(rgdal)

writeSpatialShape(gwrG$SDF, "GWR_Results")
